package com.baiytfp.hf.HFDataExchange.common.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletConfig;

import com.baiytfp.hf.baiytfp.hfutils.HFConfig;

//import com.baiytfp.hf.HFPay.module.util.model.FreemarkerUtil;
//import com.baiytfp.hf.HFPay.module.util.model.HFConfig;

/**
 * @author Steven
 * 
 *         2015年10月26日
 */

public class MailTool {

	/*
	 * 带附件的邮件发送 public static void testSendEamilWithAttah() throws Exception {
	 * List<String> list = new ArrayList(); list.add("d:/work01.txt");
	 * list.add("d:/work02.txt");
	 * 
	 * MailTool.sendEmail("带附件的邮件", "带附件的邮件content", "ct@baiytfp.com", list); }
	 */

	public static void sendEmailByFtl(String subject, String to, String ftl, Map root, ServletConfig servletConfig)
			throws Exception {
		sendEmailByFtl(subject, to, ftl, root, servletConfig, null);
	}

	public static void sendEmailByFtl(String subject, String to, String ftl, Map root, ServletConfig servletConfig,
			List<String> attachFilePathList) throws Exception {

		FreemarkerUtil fu = new FreemarkerUtil(servletConfig, ftl, HFConfig.getIstance().getPropConfig("ftl_templatePath",
				"/WEB-INF/ftl/"), "/spring/config/freemaker.properties");
		String content = fu.getPageString(root);

		List toList = new ArrayList();
		toList.add(to);
		sendEmail(subject, content, toList, null, null, attachFilePathList);
	}

	public static void sendEmail(String subject, String content, String to) throws Exception {
		sendEmail(subject, content, to, null);
	}

	public static void sendEmail(String subject, String content, String to, List<String> attachFilePathList)
			throws Exception {
		List toList = new ArrayList();
		toList.add(to);
		sendEmail(subject, content, toList, null, null, attachFilePathList);
	}

	public static void sendEmail(String subject, String content, List<String> toList, List<String> ccList,
			List<String> bccList, List<String> attachFilePathList) throws Exception {

		sendEmail("true", 
				HFConfig.getIstance().getPropConfig("email.host"), 
				HFConfig.getIstance().getPropConfig("email.user"),
				HFConfig.getIstance().getPropConfig("email.password"), 
				subject, content, toList, ccList, bccList, attachFilePathList);
	}

	/**
	 * 发送邮件方法
	 * 
	 * @param auth
	 *            是否需要验证
	 * @param host
	 *            smtp 发送主机
	 * @param user
	 *            用户名
	 * @param password
	 *            用户密码
	 * @param subject
	 *            邮件标题
	 * @param content
	 *            邮件内容
	 * @param toList
	 *            接收人
	 * @param ccList
	 *            抄送人
	 * @param bccList
	 *            密送人
	 * @param attachFilePathList
	 *            附件列表
	 * @throws Exception
	 */
	public static void sendEmail(String auth, String host, String user, String password, String subject,
			String content, List<String> toList, List<String> ccList, List<String> bccList,
			List<String> attachFilePathList) throws Exception {
		// 配置发送邮件的环境属性
		final Properties props = new Properties();
		/*
		 * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
		 * mail.user / mail.from
		 */
		// 表示SMTP发送邮件，需要进行身份验证
		props.put("mail.smtp.auth", auth);
		props.put("mail.smtp.host", host);
		// 发件人的账号
		props.put("mail.user", user);
		// 访问SMTP服务时需要提供的密码
		props.put("mail.password", password);

		// 构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = props.getProperty("mail.user");
				String password = props.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		// 使用环境属性和授权信息，创建邮件会话
		Session mailSession = Session.getInstance(props, authenticator);
		// 创建邮件消息
		MimeMessage message = new MimeMessage(mailSession);
		// 设置发件人
		InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
		message.setFrom(form);

		// 设置收件人
		if (toList != null && toList.size() > 0) {
			InternetAddress[] to = new InternetAddress[toList.size()];
			for (int i = 0; i < toList.size(); i++) {
				to[i] = new InternetAddress(toList.get(i));
			}
			message.setRecipients(RecipientType.TO, to);
		}

		// 设置抄送
		if (ccList != null && ccList.size() > 0) {
			InternetAddress[] cc = new InternetAddress[ccList.size()];
			for (int i = 0; i < ccList.size(); i++) {
				cc[i] = new InternetAddress(ccList.get(i));
			}
			message.setRecipients(RecipientType.CC, cc);
		}

		// 设置密送，其他的收件人不能看到密送的邮件地址
		if (bccList != null && bccList.size() > 0) {
			InternetAddress[] bcc = new InternetAddress[bccList.size()];
			for (int i = 0; i < bccList.size(); i++) {
				bcc[i] = new InternetAddress(bccList.get(i));
			}
			message.setRecipients(RecipientType.BCC, bcc);
		}

		// 设置邮件标题
		message.setSubject(MimeUtility.encodeText(subject, MimeUtility.mimeCharset("UTF-8"), null));

		// 设置邮件的内容体
		message.setContent(content, "text/html;charset=UTF-8");

		// 添加附件的内容
		if (attachFilePathList != null && attachFilePathList.size() > 0) {
			// 添加附件必须设置邮件类型
			MimeMultipart msgMultipart = new MimeMultipart("mixed");
			message.setContent(msgMultipart);

			Iterator<String> iterator = attachFilePathList.iterator();
			while (iterator.hasNext()) {
				String filePath = iterator.next();

				File attachment = new File(filePath);

				BodyPart attachmentBodyPart = new MimeBodyPart();
				DataSource source = new FileDataSource(attachment);
				attachmentBodyPart.setDataHandler(new DataHandler(source));

				// 网上流传的解决文件名乱码的方法，其实用MimeUtility.encodeWord就可以很方便的搞定
				// 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
				// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
				// messageBodyPart.setFileName("=?GBK?B?" +
				// enc.encode(attachment.getName().getBytes()) + "?=");

				// MimeUtility.encodeWord可以避免文件名乱码
				attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
				msgMultipart.addBodyPart(attachmentBodyPart);
			}

		}

		// 发送邮件
		Transport.send(message);
	}

	public static void testSend() throws MessagingException {
		// 配置发送邮件的环境属性
		final Properties props = new Properties();
		/*
		 * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
		 * mail.user / mail.from
		 */
		// 表示SMTP发送邮件，需要进行身份验证
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", "smtp.163.com");
		// 发件人的账号
		props.put("mail.user", "18816890913@163.com");
		// 访问SMTP服务时需要提供的密码
		props.put("mail.password", "686210563");

		// 构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = props.getProperty("mail.user");
				String password = props.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		// 使用环境属性和授权信息，创建邮件会话
		Session mailSession = Session.getInstance(props, authenticator);
		// 创建邮件消息
		MimeMessage message = new MimeMessage(mailSession);
		// 设置发件人
		InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
		message.setFrom(form);

		// 设置收件人
		InternetAddress to = new InternetAddress("526479113@qq.com");
		message.setRecipient(RecipientType.TO, to);
		//
		// // 设置抄送
		// InternetAddress cc = new InternetAddress("baiytfp@163.com");
		// message.setRecipient(RecipientType.CC, cc);
		//
		// // 设置密送，其他的收件人不能看到密送的邮件地址
		// InternetAddress bcc = new InternetAddress("ct@baiytfp.com");
		// message.setRecipient(RecipientType.BCC, bcc);

		// 设置邮件标题
		message.setSubject("测试邮件");

		// 设置邮件的内容体
		message.setContent(
				"您好：<br><br>&nbsp;&nbsp;<a href=\"http://localhost:8080/thdoc/docManage/aaa.do\" >您有一份待办公文需要处理，请点击进行处理。谢谢！</a>",
				"text/html;charset=UTF-8");
		// message.setContent("<a href='http://www.fkjava.org'>测试的HTML邮件</a>",
		// "text/html;charset=UTF-8");

		// 发送邮件
		Transport.send(message);
	}

	public static void main(String[] args) {
		try {
			testSend();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
